package com.xiaoming.module2.factory;


import com.xiaoming.module2.utils.TransactionManager;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /***
     * 获取代理对象
     * @param obj
     * @return
     */
    public Object  getJdkProxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                (Object proxy, Method method, Object[] args) -> {
                    if (!method.getName().equals("toString")) {
                        System.out.println("proxy toString: " + proxy.toString());
                    }
                    Object result = null;
                    try {
                        transactionManager.beginTransaction();
                        System.out.println("方法调用前");
                        result = method.invoke(proxy, args);
                        System.out.println("方法调用后");
                        transactionManager.commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("回滚");
                        transactionManager.rollback();
                    }
                    return result;
                }
        );
    }
}
